package com.learn.gateway.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Optional;

/**
 * @author wm
 * gateway配置类
 */
@Configuration
public class CusGatewayConfiguration {

    @Resource
    private CusGatewayProperties cusGatewayProperties;

    /**
     * 处理跨域问题
     *
     * @return corsWebFilter
     */
    @Bean
    public CorsWebFilter corsWebFilter() {
        UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        //请求来源
        Optional.ofNullable(cusGatewayProperties.getAllowedOriginPatterns()).orElse(new ArrayList<>())
                .forEach(config::addAllowedOriginPattern);
        //请求头
        Optional.ofNullable(cusGatewayProperties.getAllowedHeaders()).orElse(new ArrayList<>())
                .forEach(config::addAllowedHeader);
        //请求方法
        Optional.ofNullable(cusGatewayProperties.getAllowedMethods()).orElse(new ArrayList<>())
                .forEach(config::addAllowedMethod);
        //允许携带cookie
        config.setAllowCredentials(true);
        configSource.registerCorsConfiguration("/**", config);
        return new CorsWebFilter(configSource);
    }
}
